import psutil
import time

try:
    while True:
        # 获取 CPU 使用率  
        cpu_usage = psutil.cpu_percent(interval=1)  # interval 设置为 1 秒，获取平均值  
        print(f"CPU 使用率: {cpu_usage}%")

        # 获取内存占用情况  
        memory_info = psutil.virtual_memory()
        memory_usage = memory_info.percent
        total_memory = memory_info.total / (1024 ** 3)  # 总内存，单位为 GB  
        used_memory = memory_info.used / (1024 ** 3)  # 已使用内存，单位为 GB
        available_memory = memory_info.available / (1024 ** 3)  # 可用内存，单位为 GB  

        print(f"内存使用率: {memory_usage}%")
        print(f"总内存: {total_memory:.2f} GB")
        print(f"已使用内存: {used_memory:.2f} GB")
        print(f"可用内存: {available_memory:.2f} GB")

        # 等待一秒  
        time.sleep(1)

except KeyboardInterrupt:
    print("程序已停止.")  